import { observable, action } from 'mobx';
import { toJS } from 'mobx';
import { Toast,Tools } from 'weaver-mobile';
import { RouteLayout, SearchPage, SearchAdvanced, ListViewPage } from 'weaver-mobile-page';
import * as Api from '../../api/CommunicationApi'
import DetailStore from './DetailStore';
import ParterListStore from './ParterListStore';
import TagStore from './TagStore';
import QuitedListStore from './QuitedListStore';
import DetailParticipationStore from './DetailParticipation';
import DefalutJoinerStore from './DefalutJoiner';
const getLabel = Tools.getLabel;

const initState = {
  tagLayout: null,
  activePage: '',
  path: '',
  loading: false,
  searchValue: '',
  showCheck: false,
  visible: false,
  selectedListPageStore: [],
  labelOption: [],

  coworkLoading: false,
  coworkListStore: null,
  coworkAdSearchStore: null,
  coworkSearchPageStore: null,
  localeStorageKey: '',
  coworkSearchValue: '',
  coworkJoinType: '0',
}
const setPramas = [
  {key: 'communication', name: '协作列表', jointype: '0'},
  {key: 'join', name: '参与的协作', jointype: '6'},
  {key: 'response', name: '负责的协作', jointype: '3'},
  {key: 'createCoworkList', name: '创建的协作', jointype: '4'}
];
const template = { default: [{ key: 'col', configs: [{ key: 'col_row', configs: [{ key: 'name' }] }] }] };
export default class CommunicationStore { // 路由切换的处理 均放到了 store 的 index页面，避免互相切换找不到
  @observable createLayout = new RouteLayout.Store({ route: '/communication', id: 'create' }); // 新建协作
  @observable editLayout = new RouteLayout.Store({ route: '/communication', id: 'edit' }); // 新建协作
  @observable manageLayout = new RouteLayout.Store({ route: '/communication', id: 'manage' }); // 协作管理
  @observable detailLayout = new RouteLayout.Store({ route: '/communication', id: 'detail' }); // 相关交流
  @observable createTagLayout = new RouteLayout.Store({ route: '/communication/tag', id: 'createTag' }); // 新建标签
  @observable editTagLayout = new RouteLayout.Store({ route: '/communication/tag', id: 'editTag' }); // 编辑标签
  @observable parterListLayout = new RouteLayout.Store({ route: '/communication', id: 'parterList' }); // 请确认协作参与范围
  @observable detailStore = new DetailStore();
  @observable parterListStore = new ParterListStore();
  @observable tagStore = new TagStore();
  @observable quitedListStore = new QuitedListStore();
  @observable detailParticipationStore = new DetailParticipationStore();
  @observable defalutJoinerStore = new DefalutJoinerStore();
  // @observable tagLayout = initState.tagLayout;  // 标记为
  @observable tagLayout = new RouteLayout.Store({ route: '/communication', id: 'tag' });  // 标记为

  @observable loading = initState.loading;
  @observable path = initState.path;
  @observable activePage = initState.activePage;
  @observable searchValue = initState.searchValue;
  @observable visible = initState.visible;
  @observable showCheck = initState.showCheck;
  @observable tagOps = null; // tag 操作
  @observable selectedListPageStore = initState.selectedListPageStore; // 批量标记
  @observable isImportant = 0;
  @observable labelOption = initState.labelOption;
  
  @observable coworkLoading = initState.coworkLoading;
  @observable coworkListStore = initState.coworkListStore; // 列表Store
  @observable coworkAdSearchStore = initState.coworkAdSearchStore; // 高级搜索Store
  @observable coworkSearchPageStore = initState.coworkSearchPageStore;  // 搜索历史
  @observable localeStorageKey = initState.localeStorageKey;
  @observable coworkSearchValue = initState.coworkSearchValue; // 搜索值
  @observable coworkJoinType = initState.coworkJoinType;

  @observable pathMap = [
    { key: 'createCowork', name: '新建协作', path: `/communication/createCowork`},
    { key: 'manage', name: '标签管理', path: `/communication/manage`},
    { key: 'detail', name: '相关交流', path: `/communication/detail`},
    { key: 'tag', name: '标记为', path: `/communication/tag`},
    { key: 'createTag', name: '新建标签', path: '/communication/tag/createTag'},
    { key: 'parterList', name: '请确认协作参与范围', path: '/communication/parterList'},
    { key: 'addShare', name: '添加分享', path: '/communication/addShare'},
  ]

  @action getPath = (key) => toJS(this.pathMap).filter(v => v.key === key)[0].path;

  @action setStoreState = (params) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    })
  }

  @action clear = () => this.setStoreState(initState);

  @action inital = () => {
    this.localeStorageKey = `resultSearchHistory__${this.path}`;

    this.coworkListStore = new ListViewPage.Store({ route: this.path, id: this.activePage });
    this.coworkAdSearchStore = new SearchAdvanced.Store({ route: this.path, id: 'adSearch' });
    this.coworkSearchPageStore = new SearchPage.Store({ route: this.path, id: 'history', template });
  }

  @action getParams = (key) => toJS(setPramas).filter(v => v.key === key)[0].jointype;

  @action getCoworkViewType = async () => {
    let result = await Api.getCoworkViewType();
    return result
  }

  @action coworkChangeJoinType = async (params) => {
    await Api.coworkChangeJoinType(params)
  }

  @action
  getCoworkList = async (needLoading = true) => {
    needLoading && (this.coworkLoading = true);
    let formParams = this.coworkAdSearchStore.form.formParams;
    if(formParams.labelid&&"allTab"===formParams.labelid){
      formParams.type="all";
    }else if(formParams.labelid&&"1"===formParams.labelid){
      formParams.type="unread";
    }else if(formParams.labelid&&"2"===formParams.labelid){
      formParams.type="important";
    }else if(formParams.labelid&&"3"===formParams.labelid){
      formParams.type="hidden";
    }else if(formParams.labelid){
      //上面if可以统一走这个,暂时不做修改
      if(this.labelOption.length>0){
        for (var label of toJS(this.labelOption)) {
          if(formParams.labelid == label.key){
            formParams.type=label.labelType;
            break;
          }else{
            formParams.type="label";
          }
        }
      }else{
        formParams.type="label";
      }
    }
    let params = {
      type: 'all',
      labelid: 'allTab',
      layout: 2,
      mainid: '',
      pagesize: 30,
      pageNum: 1,
      ...formParams
    }
    let result = await Api.getCoworkList(params);
    if (result) {
      const dataKey = result.sessionkey;
      if (dataKey) {
        this.dataKey = dataKey;
        this.coworkListStore.getData({ dataKey }, () => this.coworkLoading = false, true);
      }
    }
  }

  @action searchPageClear = () => {
    localStorage.removeItem(this.localeStorageKey);
    this.coworkSearchPageStore.list.setState({ data: [] });
  }
  
  @action
  getSearchAdvancedCondition = () => {
    if (this.coworkAdSearchStore) {
      return this.coworkAdSearchStore.getData({
        url: '/api/cowork/base/getCoworkItemRecordCondition',
        method: `GET`,
      })
    }
  }
  
  @action("搜索 || 高级搜索")
  onSearch = () => {
    this.coworkListStore.clearData(); // 清除列表数据
    this.getCoworkList();
    let value = toJS(this.coworkSearchValue)
    if (value !== '') {
      let searchHistory = localStorage.getItem(this.localeStorageKey);
      searchHistory = searchHistory ? JSON.parse(searchHistory) : [];
      searchHistory = searchHistory.filter(h => h.key !== value);
      searchHistory.unshift({ key: value, name: value });
      localStorage.setItem(this.localeStorageKey, JSON.stringify(searchHistory));
    }
  }

  @action('批量标记')
  batchMark = (callback) => {
    if (toJS(this.coworkListStore).selectedRowKeys.length === 0) {
      Toast.info(getLabel(390693, '请选择要标记的协作'), 1);
    }else {
      this.selectedListPageStore = toJS(this.coworkListStore).selectedRowKeys
      if (callback) callback();
    }
  }
  
  @action('全选取消')
  onHideCheck = () => {
    this.showCheck = false;
    this.coworkListStore.selectNone();
  }

	@action('更新list数据')
  updateListData = (ids, params, isDelete = false) => {
		if(!this.coworkListStore) {
			return;
		}
    const { data, updateDataSource, setState } = this.coworkListStore;
    let curData = [];
    if (isDelete) {
      curData = toJS(data).filter(v => ids.split(',').indexOf(v.id) < 0);
    } else {
      curData = toJS(data).map(v => {
        if (ids.split(',').indexOf(v.id) > -1) {
          return {
            ...v,
            ...params,
          }
        }
        return v;
      });
    }
    Promise.all([setState({ data: curData})]).then(() => {
      this.showCheck = false;
      setState({ selectedRowKeys: [] });
      updateDataSource();
    });
  }
}